const { verify } = require('../util/jwt')
const { jwtSecret } = require('../config/config.default')
const { User } = require('../model')
module.exports = async (req,res,next) => {
  //从请求投获取token
  //验证token是否有效
  //无效 -> 响应401状态码
  //有效 则返回req
  let token = req.headers['authentication']
  token = token ? token.split('Bearer ')[1] : null
  if(!token){
    return res.status(401).end()
  }
  console.log(token)
  try {
    const decodedToken = await verify(token,jwtSecret)
    req.user = await User.findById(decodedToken.userId)
    next()
  } catch (error) {
    console.log(error)
    return res.status(401).end()
  }
}